{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1WjBv6UrUIZ7KU2x0eFP9kQgNXbv9JpwI?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>"
      ],
      "metadata": {
        "id": "O4dCWg0fFVVv"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### RAG: Retrieval-Augmented Generation with ChromaDB + Google Embeddings"
      ],
      "metadata": {
        "id": "lg5aeRkjhspy"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "id": "4SkM6nrE2i-M",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9954dd26-b02d-4ba2-eef7-58c33f60db5a"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[?25l     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/67.3 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m67.3/67.3 kB\u001b[0m \u001b[31m2.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
            "  Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
            "  Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m19.9/19.9 MB\u001b[0m \u001b[31m97.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m278.2/278.2 kB\u001b[0m \u001b[31m16.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m51.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m103.3/103.3 kB\u001b[0m \u001b[31m6.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m17.4/17.4 MB\u001b[0m \u001b[31m95.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m72.5/72.5 kB\u001b[0m \u001b[31m4.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m105.4/105.4 kB\u001b[0m \u001b[31m7.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m71.6/71.6 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m517.7/517.7 kB\u001b[0m \u001b[31m28.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m128.4/128.4 kB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.7/4.7 MB\u001b[0m \u001b[31m84.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m452.2/452.2 kB\u001b[0m \u001b[31m25.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m46.0/46.0 kB\u001b[0m \u001b[31m2.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m86.8/86.8 kB\u001b[0m \u001b[31m4.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h  Building wheel for pypika (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"
          ]
        }
      ],
      "source": [
        "!pip install -qU google-generativeai chromadb"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import google.generativeai as genai\n",
        "import chromadb\n",
        "import getpass"
      ],
      "metadata": {
        "id": "kpFR0OM_iEmq"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Get free-tier Google's Gemini API Key here: https://aistudio.google.com/app/apikey"
      ],
      "metadata": {
        "id": "KOLpdJU3iHSb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "API_KEY = getpass.getpass(\"Enter your Google API key: \")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "IpNO5XYiiIC0",
        "outputId": "39d72807-1461-49ca-8606-48a41f618154"
      },
      "execution_count": 3,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Enter your Google API key: ··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "genai.configure(api_key=API_KEY)"
      ],
      "metadata": {
        "id": "jVueK0AriODA"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class RAG:\n",
        "    def __init__(self, collection_name=\"knowledge_base\"):\n",
        "        self.model = genai.GenerativeModel(\"gemini-2.0-flash\")\n",
        "\n",
        "        # Initialize ChromaDB\n",
        "        self.chroma_client = chromadb.Client()\n",
        "        self.collection = self.chroma_client.get_or_create_collection(\n",
        "            name=collection_name,\n",
        "            metadata={\"description\": \"RAG knowledge base\"}\n",
        "        )\n",
        "        self.doc_counter = 0\n",
        "\n",
        "    def get_embedding(self, text):\n",
        "        \"\"\"Get embedding using Google's embedding model\"\"\"\n",
        "        result = genai.embed_content(\n",
        "            model=\"models/text-embedding-004\",\n",
        "            content=text,\n",
        "            task_type=\"retrieval_document\"\n",
        "        )\n",
        "        return result['embedding']\n",
        "\n",
        "    def add_document(self, content, metadata=None):\n",
        "        \"\"\"Add document with embedding to ChromaDB\"\"\"\n",
        "        doc_id = f\"doc_{self.doc_counter}\"\n",
        "        self.doc_counter += 1\n",
        "\n",
        "        # Get embedding\n",
        "        embedding = self.get_embedding(content)\n",
        "\n",
        "        # Add to ChromaDB\n",
        "        self.collection.add(\n",
        "            ids=[doc_id],\n",
        "            embeddings=[embedding],\n",
        "            documents=[content],\n",
        "            metadatas=[metadata or {}]\n",
        "        )\n",
        "\n",
        "        print(f\"✅ Added {doc_id}: {content[:60]}...\")\n",
        "        return doc_id\n",
        "\n",
        "    def retrieve(self, query, top_k=3):\n",
        "        \"\"\"Semantic search using embeddings\"\"\"\n",
        "        # Get query embedding\n",
        "        query_embedding = genai.embed_content(\n",
        "            model=\"models/text-embedding-004\",\n",
        "            content=query,\n",
        "            task_type=\"retrieval_query\"\n",
        "        )['embedding']\n",
        "\n",
        "        # Search in ChromaDB\n",
        "        results = self.collection.query(\n",
        "            query_embeddings=[query_embedding],\n",
        "            n_results=top_k\n",
        "        )\n",
        "\n",
        "        # Format results\n",
        "        docs = []\n",
        "        if results['documents'] and results['documents'][0]:\n",
        "            for i, (doc, metadata, distance) in enumerate(zip(\n",
        "                results['documents'][0],\n",
        "                results['metadatas'][0],\n",
        "                results['distances'][0]\n",
        "            )):\n",
        "                docs.append({\n",
        "                    \"content\": doc,\n",
        "                    \"metadata\": metadata,\n",
        "                    \"similarity\": 1 - distance  # Convert distance to similarity\n",
        "                })\n",
        "\n",
        "        return docs\n",
        "\n",
        "    def generate_response(self, query, retrieved_docs):\n",
        "        \"\"\"Generate answer using retrieved context\"\"\"\n",
        "        if not retrieved_docs:\n",
        "            return \"No relevant information found.\"\n",
        "\n",
        "        # Build context from retrieved docs\n",
        "        context = \"\\n\\n\".join([\n",
        "            f\"Document {i+1} (relevance: {doc['similarity']:.2f}):\\n{doc['content']}\"\n",
        "            for i, doc in enumerate(retrieved_docs)\n",
        "        ])\n",
        "\n",
        "        prompt = f\"\"\"Answer the question using the provided documents. Cite which document(s) you use.\n",
        "\n",
        "        Context:\n",
        "        {context}\n",
        "\n",
        "        Question: {query}\n",
        "\n",
        "        Answer:\"\"\"\n",
        "\n",
        "        response = self.model.generate_content(prompt).text\n",
        "        return response.strip()\n",
        "\n",
        "    def query(self, user_input, top_k=3):\n",
        "        \"\"\"Full RAG pipeline\"\"\"\n",
        "        print(f\"\\n{'='*60}\")\n",
        "        print(f\"❓ Query: {user_input}\")\n",
        "        print(f\"{'='*60}\\n\")\n",
        "\n",
        "        # Retrieve relevant documents\n",
        "        print(f\"🔍 Retrieving top {top_k} relevant documents...\")\n",
        "        docs = self.retrieve(user_input, top_k)\n",
        "\n",
        "        if docs:\n",
        "            print(f\"📚 Found {len(docs)} documents:\\n\")\n",
        "            for i, doc in enumerate(docs, 1):\n",
        "                print(f\"   {i}. [Similarity: {doc['similarity']:.3f}]\")\n",
        "                print(f\"      {doc['content'][:80]}...\\n\")\n",
        "        else:\n",
        "            print(\"   No relevant documents found.\\n\")\n",
        "\n",
        "        # Generate response\n",
        "        print(\"✨ Generating response...\\n\")\n",
        "        response = self.generate_response(user_input, docs)\n",
        "\n",
        "        print(f\"{'='*60}\")\n",
        "        print(f\"💬 Answer:\")\n",
        "        print(f\"{'='*60}\")\n",
        "        print(response)\n",
        "        print()\n",
        "\n",
        "        return response\n",
        "\n",
        "    def get_stats(self):\n",
        "        \"\"\"Get collection statistics\"\"\"\n",
        "        count = self.collection.count()\n",
        "        print(f\"📊 Knowledge Base: {count} documents\")"
      ],
      "metadata": {
        "id": "I5Uw_Q37iQEO"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Example 1: Company Knowledge Base\n",
        "print(\"=\"*60)\n",
        "print(\"EXAMPLE 1: Company Knowledge Base\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "company_rag = RAG(\"company_kb\")\n",
        "\n",
        "# Add documents\n",
        "company_rag.add_document(\n",
        "    \"Full-time employees receive 15 days of paid vacation per year. Part-time employees \"\n",
        "    \"receive pro-rated vacation days. All vacation requests must be approved by your \"\n",
        "    \"direct manager at least 2 weeks in advance. Unused vacation days do not roll over.\",\n",
        "    {\"department\": \"HR\", \"type\": \"vacation_policy\"}\n",
        ")\n",
        "\n",
        "company_rag.add_document(\n",
        "    \"Employees are entitled to 10 sick days per year. For absences of 1-2 days, no \"\n",
        "    \"medical documentation is required. For extended illness beyond 3 days, a doctor's \"\n",
        "    \"note must be submitted to HR.\",\n",
        "    {\"department\": \"HR\", \"type\": \"sick_leave\"}\n",
        ")\n",
        "\n",
        "company_rag.add_document(\n",
        "    \"To connect to company VPN: Download Cisco AnyConnect from the IT portal. \"\n",
        "    \"Use your company email and standard password. If you encounter connection issues, \"\n",
        "    \"contact IT helpdesk at extension 5555 or helpdesk@company.com.\",\n",
        "    {\"department\": \"IT\", \"type\": \"vpn_guide\"}\n",
        ")\n",
        "\n",
        "company_rag.add_document(\n",
        "    \"All business expenses must be submitted through Expensify within 30 days of purchase. \"\n",
        "    \"Receipts are mandatory. Expenses over $500 require manager approval. Reimbursement \"\n",
        "    \"is processed within 5-7 business days after approval.\",\n",
        "    {\"department\": \"Finance\", \"type\": \"expense_policy\"}\n",
        ")\n",
        "\n",
        "company_rag.add_document(\n",
        "    \"Remote work policy: Employees can work remotely up to 3 days per week with manager \"\n",
        "    \"approval. Must be available during core hours 10am-3pm. Home office stipend of $500 \"\n",
        "    \"available annually for equipment purchases.\",\n",
        "    {\"department\": \"HR\", \"type\": \"remote_work\"}\n",
        ")\n",
        "\n",
        "company_rag.get_stats()\n",
        "\n",
        "# Test semantic search\n",
        "company_rag.query(\"How many days off do I get for vacation?\")\n",
        "company_rag.query(\"I'm sick, what's the policy?\")\n",
        "company_rag.query(\"How do I connect to VPN from home?\")\n",
        "company_rag.query(\"Can I work from home?\")\n",
        "\n",
        "\n",
        "# Example 2: Technical Documentation\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 2: Technical Documentation\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "tech_rag = RAG(\"tech_docs\")\n",
        "\n",
        "tech_rag.add_document(\n",
        "    \"Authentication uses JWT Bearer tokens. Obtain a token by sending POST request to \"\n",
        "    \"/api/v1/auth with JSON body containing username and password. Token expires after \"\n",
        "    \"24 hours. Include token in Authorization header: 'Bearer <token>'.\",\n",
        "    {\"category\": \"authentication\", \"version\": \"v1\"}\n",
        ")\n",
        "\n",
        "tech_rag.add_document(\n",
        "    \"User management endpoints: GET /api/v1/users (list all users), \"\n",
        "    \"POST /api/v1/users (create new user, requires admin role), \"\n",
        "    \"PUT /api/v1/users/{id} (update user), DELETE /api/v1/users/{id} (delete user, admin only). \"\n",
        "    \"All endpoints require authentication.\",\n",
        "    {\"category\": \"endpoints\", \"resource\": \"users\"}\n",
        ")\n",
        "\n",
        "tech_rag.add_document(\n",
        "    \"Rate limiting: API requests are limited to 100 requests per minute per API key. \"\n",
        "    \"Exceeded limits return 429 Too Many Requests. Rate limit info in response headers: \"\n",
        "    \"X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset.\",\n",
        "    {\"category\": \"rate_limiting\"}\n",
        ")\n",
        "\n",
        "tech_rag.add_document(\n",
        "    \"Error handling: API returns standard HTTP status codes. 400 for bad requests, \"\n",
        "    \"401 for unauthorized, 403 for forbidden, 404 for not found, 500 for server errors. \"\n",
        "    \"Error responses include JSON with 'error' (code) and 'message' (description) fields.\",\n",
        "    {\"category\": \"errors\"}\n",
        ")\n",
        "\n",
        "tech_rag.get_stats()\n",
        "\n",
        "tech_rag.query(\"How do I authenticate?\")\n",
        "tech_rag.query(\"What happens if I make too many requests?\")\n",
        "tech_rag.query(\"How do I create a new user?\")\n",
        "\n",
        "\n",
        "# Example 3: Research Papers (Semantic Understanding)\n",
        "print(\"\\n\" + \"=\"*60)\n",
        "print(\"EXAMPLE 3: Research Database (Semantic Search)\")\n",
        "print(\"=\"*60)\n",
        "\n",
        "research_rag = RAG(\"research\")\n",
        "\n",
        "research_rag.add_document(\n",
        "    \"Remote work productivity study 2023: Survey of 5000 employees found 65% report \"\n",
        "    \"increased productivity when working remotely. Key contributing factors include \"\n",
        "    \"flexible scheduling, elimination of commute time, and personalized work environment. \"\n",
        "    \"However, 28% experienced productivity decline due to home distractions.\",\n",
        "    {\"year\": 2023, \"topic\": \"remote_work\", \"type\": \"survey\"}\n",
        ")\n",
        "\n",
        "research_rag.add_document(\n",
        "    \"Challenges of distributed teams: Research shows 40% of remote workers struggle with \"\n",
        "    \"work-life balance. Communication gaps reported in 35% of fully remote teams. \"\n",
        "    \"Social isolation affects 30% of remote employees. Regular video meetings and virtual \"\n",
        "    \"social events help mitigate these issues.\",\n",
        "    {\"year\": 2023, \"topic\": \"remote_challenges\"}\n",
        ")\n",
        "\n",
        "research_rag.add_document(\n",
        "    \"Hybrid work model analysis 2024: Companies implementing 3-2 model (3 days office, \"\n",
        "    \"2 days remote) report 22% higher employee satisfaction compared to fully office or \"\n",
        "    \"fully remote. This model balances collaboration benefits with flexibility. \"\n",
        "    \"Wednesday is most common mandatory office day.\",\n",
        "    {\"year\": 2024, \"topic\": \"hybrid_work\"}\n",
        ")\n",
        "\n",
        "research_rag.add_document(\n",
        "    \"Impact of AI on software development: Study shows developers using AI assistants \"\n",
        "    \"complete tasks 35% faster. Code quality metrics remain similar. 78% of developers \"\n",
        "    \"report AI tools helpful for boilerplate code. Learning curve for effective AI \"\n",
        "    \"prompting takes 2-3 weeks.\",\n",
        "    {\"year\": 2024, \"topic\": \"ai_development\"}\n",
        ")\n",
        "\n",
        "research_rag.get_stats()\n",
        "\n",
        "# Semantic search should find relevant docs even with different wording\n",
        "research_rag.query(\"What are the benefits and drawbacks of working from home?\")\n",
        "research_rag.query(\"What's the best office-remote split?\")\n",
        "research_rag.query(\"How does artificial intelligence help programmers?\")\n",
        "\n",
        "print(\"\\n✅ RAG with ChromaDB + Google Embeddings Complete!\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "OQKicsZNibYL",
        "outputId": "413f9477-4608-4b3f-87c1-8c81b9bf315a"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "============================================================\n",
            "EXAMPLE 1: Company Knowledge Base\n",
            "============================================================\n",
            "✅ Added doc_0: Full-time employees receive 15 days of paid vacation per yea...\n",
            "✅ Added doc_1: Employees are entitled to 10 sick days per year. For absence...\n",
            "✅ Added doc_2: To connect to company VPN: Download Cisco AnyConnect from th...\n",
            "✅ Added doc_3: All business expenses must be submitted through Expensify wi...\n",
            "✅ Added doc_4: Remote work policy: Employees can work remotely up to 3 days...\n",
            "📊 Knowledge Base: 5 documents\n",
            "\n",
            "============================================================\n",
            "❓ Query: How many days off do I get for vacation?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.408]\n",
            "      Full-time employees receive 15 days of paid vacation per year. Part-time employe...\n",
            "\n",
            "   2. [Similarity: 0.234]\n",
            "      Employees are entitled to 10 sick days per year. For absences of 1-2 days, no me...\n",
            "\n",
            "   3. [Similarity: 0.054]\n",
            "      Remote work policy: Employees can work remotely up to 3 days per week with manag...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "Full-time employees receive 15 days of paid vacation per year (Document 1). Part-time employees receive pro-rated vacation days (Document 1).\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: I'm sick, what's the policy?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.284]\n",
            "      Employees are entitled to 10 sick days per year. For absences of 1-2 days, no me...\n",
            "\n",
            "   2. [Similarity: -0.031]\n",
            "      Full-time employees receive 15 days of paid vacation per year. Part-time employe...\n",
            "\n",
            "   3. [Similarity: -0.045]\n",
            "      Remote work policy: Employees can work remotely up to 3 days per week with manag...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "According to Document 1, employees are entitled to 10 sick days per year. For absences of 1-2 days, no medical documentation is required. For extended illness beyond 3 days, a doctor's note must be submitted to HR.\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: How do I connect to VPN from home?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.338]\n",
            "      To connect to company VPN: Download Cisco AnyConnect from the IT portal. Use you...\n",
            "\n",
            "   2. [Similarity: -0.164]\n",
            "      Remote work policy: Employees can work remotely up to 3 days per week with manag...\n",
            "\n",
            "   3. [Similarity: -0.274]\n",
            "      All business expenses must be submitted through Expensify within 30 days of purc...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "To connect to the company VPN from home: Download Cisco AnyConnect from the IT portal. Use your company email and standard password. If you encounter connection issues, contact IT helpdesk at extension 5555 or helpdesk@company.com (Document 1).\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: Can I work from home?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.204]\n",
            "      Remote work policy: Employees can work remotely up to 3 days per week with manag...\n",
            "\n",
            "   2. [Similarity: -0.070]\n",
            "      Employees are entitled to 10 sick days per year. For absences of 1-2 days, no me...\n",
            "\n",
            "   3. [Similarity: -0.085]\n",
            "      Full-time employees receive 15 days of paid vacation per year. Part-time employe...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "Yes, you can work from home up to 3 days per week with manager approval (Document 1).\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 2: Technical Documentation\n",
            "============================================================\n",
            "✅ Added doc_0: Authentication uses JWT Bearer tokens. Obtain a token by sen...\n",
            "✅ Added doc_1: User management endpoints: GET /api/v1/users (list all users...\n",
            "✅ Added doc_2: Rate limiting: API requests are limited to 100 requests per ...\n",
            "✅ Added doc_3: Error handling: API returns standard HTTP status codes. 400 ...\n",
            "📊 Knowledge Base: 4 documents\n",
            "\n",
            "============================================================\n",
            "❓ Query: How do I authenticate?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.236]\n",
            "      Authentication uses JWT Bearer tokens. Obtain a token by sending POST request to...\n",
            "\n",
            "   2. [Similarity: 0.028]\n",
            "      User management endpoints: GET /api/v1/users (list all users), POST /api/v1/user...\n",
            "\n",
            "   3. [Similarity: -0.080]\n",
            "      Rate limiting: API requests are limited to 100 requests per minute per API key. ...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "Authenticate using JWT Bearer tokens. Obtain a token by sending a POST request to /api/v1/auth with a JSON body containing your username and password. Include the token in the Authorization header as 'Bearer <token>'. (Document 1)\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: What happens if I make too many requests?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.287]\n",
            "      Rate limiting: API requests are limited to 100 requests per minute per API key. ...\n",
            "\n",
            "   2. [Similarity: 0.044]\n",
            "      Error handling: API returns standard HTTP status codes. 400 for bad requests, 40...\n",
            "\n",
            "   3. [Similarity: -0.068]\n",
            "      Authentication uses JWT Bearer tokens. Obtain a token by sending POST request to...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "If you make too many API requests, you will receive a 429 Too Many Requests error. The API is limited to 100 requests per minute per API key. (Document 1)\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: How do I create a new user?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.232]\n",
            "      User management endpoints: GET /api/v1/users (list all users), POST /api/v1/user...\n",
            "\n",
            "   2. [Similarity: 0.027]\n",
            "      Authentication uses JWT Bearer tokens. Obtain a token by sending POST request to...\n",
            "\n",
            "   3. [Similarity: -0.144]\n",
            "      Error handling: API returns standard HTTP status codes. 400 for bad requests, 40...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "To create a new user, send a POST request to `/api/v1/users`. This action requires an admin role and authentication. (Document 1) You'll need a JWT Bearer token obtained by sending a POST request to `/api/v1/auth` with your username and password. Then, include the token in the Authorization header as 'Bearer <token>'. (Document 2)\n",
            "\n",
            "\n",
            "============================================================\n",
            "EXAMPLE 3: Research Database (Semantic Search)\n",
            "============================================================\n",
            "✅ Added doc_0: Remote work productivity study 2023: Survey of 5000 employee...\n",
            "✅ Added doc_1: Challenges of distributed teams: Research shows 40% of remot...\n",
            "✅ Added doc_2: Hybrid work model analysis 2024: Companies implementing 3-2 ...\n",
            "✅ Added doc_3: Impact of AI on software development: Study shows developers...\n",
            "📊 Knowledge Base: 4 documents\n",
            "\n",
            "============================================================\n",
            "❓ Query: What are the benefits and drawbacks of working from home?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.272]\n",
            "      Remote work productivity study 2023: Survey of 5000 employees found 65% report i...\n",
            "\n",
            "   2. [Similarity: 0.196]\n",
            "      Challenges of distributed teams: Research shows 40% of remote workers struggle w...\n",
            "\n",
            "   3. [Similarity: 0.045]\n",
            "      Hybrid work model analysis 2024: Companies implementing 3-2 model (3 days office...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "Based on the provided documents, the benefits of working from home include increased productivity (reported by 65% of employees) due to flexible scheduling, elimination of commute time, and a personalized work environment (Document 1). However, drawbacks include a potential decline in productivity due to home distractions (28% in Document 1), struggles with work-life balance (40% in Document 2), communication gaps (35% in fully remote teams per Document 2), and social isolation (affecting 30% of remote employees per Document 2).\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: What's the best office-remote split?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.292]\n",
            "      Hybrid work model analysis 2024: Companies implementing 3-2 model (3 days office...\n",
            "\n",
            "   2. [Similarity: 0.220]\n",
            "      Remote work productivity study 2023: Survey of 5000 employees found 65% report i...\n",
            "\n",
            "   3. [Similarity: 0.205]\n",
            "      Challenges of distributed teams: Research shows 40% of remote workers struggle w...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "According to a 2024 analysis, companies using a 3-2 hybrid model (3 days in the office, 2 days remote) report 22% higher employee satisfaction compared to fully office or fully remote setups (Document 1). This model aims to balance the benefits of collaboration with the flexibility of remote work (Document 1).\n",
            "\n",
            "\n",
            "============================================================\n",
            "❓ Query: How does artificial intelligence help programmers?\n",
            "============================================================\n",
            "\n",
            "🔍 Retrieving top 3 relevant documents...\n",
            "📚 Found 3 documents:\n",
            "\n",
            "   1. [Similarity: 0.319]\n",
            "      Impact of AI on software development: Study shows developers using AI assistants...\n",
            "\n",
            "   2. [Similarity: -0.287]\n",
            "      Challenges of distributed teams: Research shows 40% of remote workers struggle w...\n",
            "\n",
            "   3. [Similarity: -0.295]\n",
            "      Remote work productivity study 2023: Survey of 5000 employees found 65% report i...\n",
            "\n",
            "✨ Generating response...\n",
            "\n",
            "============================================================\n",
            "💬 Answer:\n",
            "============================================================\n",
            "According to Document 1, AI assistants help developers complete tasks 35% faster. Also, 78% of developers find AI tools helpful for boilerplate code.\n",
            "\n",
            "\n",
            "✅ RAG with ChromaDB + Google Embeddings Complete!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "IKYZFdr2i5jT"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}